<template>
  <div class="app-container">
    <el-card v-if="inspiration" class="inspiration-detail">
      <div class="inspiration-header">
        <h1>{{ inspiration.name }}</h1>
        <el-tag :type="stateTagType(inspiration.state)" size="large">
          {{ stateLabel(inspiration.state) }}
        </el-tag>
      </div>

      <el-divider />

      <el-row :gutter="20">
        <el-col :span="12">
          <el-descriptions title="灵感基本信息" :column="1" border>
            <el-descriptions-item label="灵感ID">{{
              inspiration.id
            }}</el-descriptions-item>
            <el-descriptions-item label="灵感名称">{{
              inspiration.name
            }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{
              inspiration.createTime
            }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{
              inspiration.updateTime
            }}</el-descriptions-item>
            <el-descriptions-item label="灵感描述">{{
              inspiration.description
            }}</el-descriptions-item>
          </el-descriptions>
        </el-col>

        <el-col :span="12">
          <el-card class="image-card">
            <template #header>
              <span>灵感图片</span>
            </template>
            <div class="image-container">
              <el-image
                v-if="inspiration.url"
                :src="inspiration.url"
                :preview-src-list="[inspiration.url]"
                fit="contain"
                class="inspiration-image" />
              <div v-else class="no-image">暂无图片</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-divider />

      <div class="sku-section">
        <h2>相关商品</h2>
        <el-button @click="goBack">返回</el-button>
        <el-button type="primary" @click="handleAddProduct" icon="Plus"
          >添加商品</el-button
        >
        <br /><br />
        <el-table :data="inspiration.relatedSkus" border style="width: 80%">
          <el-table-column prop="code" label="SKU编码" width="180" />
          <el-table-column label="商品名称" max-width="50">
            <template #default="scope">
              <div class="sku-name">{{ getSkuName(scope.row) }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格" width="130">
            <template #default="scope"> ${{ scope.row.price }} </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存" width="130" />

          <el-table-column label="商品图片" width="120">
            <template #default="scope">
              <el-image
                v-if="scope.row.image"
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
                fit="cover"
                style="width: 80px; height: 80px; border-radius: 4px" />
              <span v-else>无图片</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button
                type="danger"
                link
                @click="handleRemoveProduct(scope.row)"
                icon="Delete">
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 添加商品对话框 -->
      <el-dialog
        title="添加相关商品"
        v-model="addProductDialog.visible"
        width="600px"
        append-to-body>
        <el-form
          ref="addProductFormRef"
          :model="addProductDialog.form"
          :rules="addProductDialog.rules"
          label-width="100px">
          <el-form-item label="商品SKU" prop="skuId">
            <el-select
              v-model="addProductDialog.form.skuId"
              placeholder="请选择商品SKU"
              filterable
              remote
              :remote-method="searchSku"
              :loading="addProductDialog.loading"
              style="width: 100%">
              <el-option
                v-for="item in skuOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
                <span style="float: left">{{ item.name }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancelAddProduct">取 消</el-button>
            <el-button type="primary" @click="submitAddProduct"
              >确 定</el-button
            >
          </div>
        </template>
      </el-dialog>
    </el-card>

    <div v-else class="loading-container">
      <el-skeleton v-if="loading" :rows="10" animated />
      <el-empty v-else description="灵感不存在" />
    </div>
  </div>
</template>

<script setup name="InspirationDetail">
import { ref, onMounted, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getCurrentInstance } from "vue";
import { getSkuNameList } from "@/api/product/sku";
import {
  getInspiration,
  addInspirationSku,
  delInspirationSku,
} from "@/api/customerService/inspiration";

const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

const inspiration = ref(null);
const loading = ref(true);

// 灵感状态标签类型映射
const stateTagType = (state) => {
  const stateMap = {
    0: "info", // 未启用
    1: "success", // 已启用
  };
  return stateMap[state] || "";
};

// 灵感状态标签文本映射
const stateLabel = (state) => {
  const stateMap = {
    0: "未启用",
    1: "已启用",
  };
  return stateMap[state] || "未知状态";
};

// 添加商品对话框状态
const addProductDialog = reactive({
  visible: false,
  loading: false,
  form: {
    skuId: null,
  },
  rules: {
    skuId: [{ required: true, message: "请选择商品SKU", trigger: "change" }],
  },
});

// SKU选项
const skuOptions = ref([]);

// 获取灵感详情
const fetchInspirationDetail = async (id) => {
  try {
    loading.value = true;
    const response = await getInspiration(id);
    inspiration.value = response.data;
    console.log(inspiration.value, "灵感详情");
    // 确保数据类型正确
    if (inspiration.value) {
      inspiration.value.state = inspiration.value.state?.toString();
    }
  } catch (error) {
    console.error("获取灵感详情失败:", error);
    proxy.$modal.msgError("获取灵感详情失败");
  } finally {
    loading.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 处理添加商品按钮点击
const handleAddProduct = () => {
  addProductDialog.visible = true;
  addProductDialog.form = {
    skuId: null,
  };
  // 初始化加载SKU列表
  searchSku("");
};

// 搜索SKU
const searchSku = async (query) => {
  addProductDialog.loading = true;
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      skuName: query,
    };
    const response = await getSkuNameList(params);
    skuOptions.value = response.data.map((item) => ({
      id: item.id,
      name: item.skuName,
    }));
  } catch (error) {
    console.error("获取SKU列表失败:", error);
    proxy.$modal.msgError("获取SKU列表失败");
  } finally {
    addProductDialog.loading = false;
  }
};

// 取消添加商品
const cancelAddProduct = () => {
  addProductDialog.visible = false;
  proxy.resetForm("addProductFormRef");
};

// 提交添加商品
const submitAddProduct = () => {
  proxy.$refs.addProductFormRef.validate(async (valid) => {
    if (valid) {
      try {
        // 这里需要根据实际API调整参数和调用方式
        const params = {
          inspirationId: inspiration.value.id,
          skuIds: [addProductDialog.form.skuId],
        };
        console.log(params);
        const res = await addInspirationSku(params);
        proxy.$modal.msgSuccess("添加商品成功");
        cancelAddProduct();
        // 重新加载灵感详情
        fetchInspirationDetail(inspiration.value.id);
      } catch (error) {
        console.error("添加商品失败:", error);
        proxy.$modal.msgError("添加商品失败");
      }
    }
  });
};

// 处理移除商品
const handleRemoveProduct = async (row) => {
  try {
    await proxy.$modal.confirm(
      `确定要从灵感中移除商品 "${getSkuName(row)}" 吗？`
    );
    console.log(row.id);
    let params = {
      inspirationId: inspiration.value.id,
      skuIds: [row.id],
    };
    const response = await delInspirationSku(params);
    if (response.code === 200) {
      proxy.$modal.msgSuccess("移除商品成功");
      // 重新加载灵感详情
      fetchInspirationDetail(inspiration.value.id);
    } else {
      proxy.$modal.msgError("移除商品失败: " + response.msg);
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("移除商品失败:", error);
      proxy.$modal.msgError("移除商品失败:" + (error.message || error));
    }
  }
};

// 获取SKU名称（从规格信息生成）
const getSkuName = (row) => {
  // 如果有skuName直接使用，否则从规格信息生成
  if (row.skuName) return row.skuName;

  // 从规格名和规格值组合生成商品名称
  if (row.specNameGroup && row.specValueGroup && row.specNameGroup.length > 0) {
    return (
      row.specNameGroup[0] +
      ": " +
      row.specValueGroup[0] +
      " - " +
      row.specNameGroup[1] +
      ": " +
      row.specValueGroup[1]
    );
  }
  return "未命名商品";
};

onMounted(() => {
  const inspirationId = route.params.id;
  if (inspirationId) {
    fetchInspirationDetail(inspirationId);
  } else {
    loading.value = false;
  }
});
</script>

<style lang="scss" scoped>
.inspiration-detail {
  .inspiration-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h1 {
      margin: 0;
      font-size: 24px;
      font-weight: bold;
    }
  }

  .image-card {
    height: 100%;

    .image-container {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 300px;

      .inspiration-image {
        max-width: 100%;
        max-height: 300px;
      }

      .no-image {
        color: #909399;
        font-size: 14px;
      }
    }
  }

  .sku-section {
    margin-top: 20px;

    .sku-name {
      font-weight: 500;
    }
  }
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}
</style>
